<?php
/** A功能的接口 */
interface FeatureA
{
    public function setEntity($entity);
    public function say();
}
/** B功能的抽象类 */
abstract class FeatureB
{
    public $entity=null;
    public function setEntity($entity){
        $this->entity=$entity;
        return $this;
    }
    abstract public function greet();
}

/**
 * 实体
 */
class Entity
{
    /** @var FeatureA $feature_a */
    public $feature_a=null;
    /** @var FeatureB $feature_b */
    public $feature_b=null;
    /**
     * @param FeatureA $feature_a 必选
     * @param FeatureB $feature_b 可选
     */
    public function __construct($feature_a, $feature_b=null)
    {
        $this->feature_a=$feature_a->setEntity($this);
        if($feature_b){
            $this->feature_b=$feature_b->setEntity($this);
        }
    }
    /** 直接调用功能类中的方法 */
    public function __call($name, $arguments)
    {
        $feature = in_array($name, ["say"]) ? $this->feature_a : $this->feature_b;
        return call_user_func_array([$feature,$name],$arguments);
    }
    /** 可选的方法提供默认的实现 */
    public function greet()
    {
        if($this->feature_b) return $this->feature_b->greet();
        echo "hello,this is Entity\r\n";
    }
}
/** A功能的实现 */
class ImplementA implements FeatureA
{
    public function setEntity($entity)
    {
        $this->entity=$entity;
        return $this;
    }
    public function say()
    {
        $entity=get_class($this->entity);
        $implement=get_class();
        echo "this is $entity with $implement \r\n";
    }
}
class ImplementB extends FeatureB
{
    public function greet()
    {
        $entity=get_class($this->entity);
        $implement=get_class();
        echo "hello,this is $entity with $implement \r\n";
    }
}

header('Content-Type: text/plain');

$entity=new Entity(new ImplementA);
$entity->say();
$entity->greet();

$entity=new Entity(new ImplementA,new ImplementB);
$entity->greet();


